import { useState, useEffect } from 'react';
import { Table, Typography, message, Space, Input, Button } from 'antd';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import { usersApi } from '../../utils/api';

const { Title } = Typography;

interface User {
  id: number;
  openid: string;
  nickname: string | null;
  avatar: string | null;
  created_at: string;
  updated_at: string;
}

export default function UserManagement() {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchOpenid, setSearchOpenid] = useState('');

  // 加载用户列表
  const loadUsers = async (openid?: string) => {
    setLoading(true);
    try {
      if (openid) {
        // 通过openid查询单个用户
        const user = await usersApi.getUserByOpenid(openid);
        setUsers(user ? [user] : []);
        setPagination(prev => ({ ...prev, total: user ? 1 : 0 }));
      } else {
        // 注意：后端目前没有用户列表接口，这里显示提示
        // 实际应该扩展后端添加用户列表接口
        message.info('后端暂未提供用户列表接口，请通过openid搜索');
        setUsers([]);
        setPagination(prev => ({ ...prev, total: 0 }));
      }
    } catch (error: any) {
      if (error.message.includes('404')) {
        message.warning('未找到该用户');
        setUsers([]);
      } else {
        message.error('加载用户失败：' + error.message);
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    // 初始不加载，等待用户搜索
  }, []);

  const handleSearch = () => {
    if (searchOpenid.trim()) {
      loadUsers(searchOpenid.trim());
    } else {
      message.warning('请输入openid');
    }
  };

  const handleReset = () => {
    setSearchOpenid('');
    setUsers([]);
    setPagination(prev => ({ ...prev, current: 1, total: 0 }));
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: 'OpenID',
      dataIndex: 'openid',
      key: 'openid',
      ellipsis: true,
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
      render: (text: string | null) => text || '-',
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      key: 'avatar',
      render: (url: string | null) => 
        url ? (
          <img src={url} alt="avatar" style={{ width: 40, height: 40, borderRadius: '50%' }} />
        ) : (
          '-'
        ),
    },
    {
      title: '注册时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (text: string) => new Date(text).toLocaleString('zh-CN'),
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      key: 'updated_at',
      render: (text: string) => new Date(text).toLocaleString('zh-CN'),
    },
  ];

  return (
    <div>
      <Space style={{ marginBottom: 16 }}>
        <Input
          placeholder="请输入用户OpenID搜索"
          value={searchOpenid}
          onChange={(e) => setSearchOpenid(e.target.value)}
          onPressEnter={handleSearch}
          style={{ width: 300 }}
        />
        <Button 
          type="primary" 
          icon={<SearchOutlined />} 
          onClick={handleSearch}
        >
          搜索
        </Button>
        <Button 
          icon={<ReloadOutlined />} 
          onClick={handleReset}
        >
          重置
        </Button>
      </Space>

      <Table<User> 
        columns={columns} 
        dataSource={users} 
        rowKey="id" 
        loading={loading}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
          onChange: (page, pageSize) => {
            setPagination(prev => ({ ...prev, current: page, pageSize }));
          },
        }}
      />
      
      <div style={{ marginTop: 16, color: '#999', fontSize: '12px' }}>
        <p>提示：目前后端暂未提供用户列表接口，请通过OpenID搜索单个用户。</p>
        <p>如需用户列表功能，需要扩展后端API添加用户列表接口。</p>
      </div>
    </div>
  );
}